package msgtunnel

import (
	"fronter/msgproto"
	"net"

	"github.com/sirupsen/logrus"
	"google.golang.org/protobuf/proto"
)

//用于维护单个tcpClient客户端的连接,用于实现ClientCall接口
type tcpClient struct {
	conn net.Conn
}

func (c tcpClient) handleMsgFromClient() {

	for {
		//读
		buffer := make([]byte, 4096)
		read_size, err := c.conn.Read(buffer)
		if err != nil {
			logrus.Errorln("read from :", c.conn.RemoteAddr().String(), " error:", err.Error())
			c.conn.Close()
			return
		}
		//解包处理
		go c.handleRequest(buffer[0:read_size])
	}
}

func (c tcpClient) handleRequest(req_buffer []byte) {
	var transPack msgproto.TransPack
	proto.Unmarshal(req_buffer, &transPack)
	transPack.Rescode = 200
	cbfunc, iscbFind := reqHandleFunc[transPack.ProtoName]
	if !iscbFind {
		logrus.Errorln("can't find cb func to handle:", transPack.ProtoName)
		transPack.Package = []byte{}
		transPack.Rescode = 504
		return
	}
	res_proto := cbfunc(req_buffer) //直接交给函数处理
	res_buffer, _ := proto.Marshal(res_proto)
	transPack.ProtoName = string(res_proto.ProtoReflect().Descriptor().FullName())
	transPack.Package = res_buffer //填充回包
	transPack_buffer, _ := proto.Marshal(&transPack)
	_, err := c.conn.Write(transPack_buffer) //回包给客户端
	if err != nil {
		logrus.Error("write to ", c.conn.RemoteAddr().String(), " failed! err:", err.Error())
		return
	}
	//logrus.Info(transPack_buffer)
}
